#include "viewdocumentslistmodel.h"
#include "application.h"
#include <QVariant>

ViewDocumentsListModel::ViewDocumentsListModel(QObject *parent) :
    QAbstractListModel(parent)
{
}

Qt::ItemFlags ViewDocumentsListModel::flags(const QModelIndex &index) const
{
    return Qt::ItemIsSelectable | Qt::ItemIsEnabled ;
}

int ViewDocumentsListModel::rowCount(const QModelIndex &parent) const
{
    return Application::app().documents().count();
}

int ViewDocumentsListModel::columnCount(const QModelIndex &parent) const
{
    return 1;
}

QVariant ViewDocumentsListModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
         return QVariant();

    if (index.row() >= m_docs.count())
         return QVariant();

    if (role == Qt::DisplayRole)
    {
         return m_docs.at(index.row())->title();
    }
    else if(role == Qt::UserRole)
    {
        return QVariant::fromValue<Document*>(m_docs.at(index.row()));
    }
    else
         return QVariant();
}


void ViewDocumentsListModel::addDocument(QPointer<Document> doc)
{
    beginInsertRows(QModelIndex(), m_docs.count(), m_docs.count());
    m_docs.append(doc);
    endInsertRows();
}

void ViewDocumentsListModel::removeDocument(QPointer<Document> doc)
{
    int index = m_docs.indexOf(doc);

    beginRemoveRows(QModelIndex(), index, index);
    m_docs.removeOne(doc);
    endRemoveRows();
}

int ViewDocumentsListModel::docIndexInModel(QPointer<Document> doc)
{
    return m_docs.indexOf(doc);
}
